package cn.tedu.csmall.order.webapi.service.impl;

import cn.tedu.csmall.cart.service.ICartService;
import cn.tedu.csmall.commons.pojo.order.dto.OrderAddDTO;
import cn.tedu.csmall.commons.pojo.order.model.OrderTbl;
import cn.tedu.csmall.commons.pojo.stock.dto.StockReduceCountDTO;
import cn.tedu.csmall.commons.restful.JsonPage;
import cn.tedu.csmall.commons.restful.JsonResult;
import cn.tedu.csmall.order.service.IOrderService;
import cn.tedu.csmall.order.webapi.mapper.OrderMapper;
import cn.tedu.csmall.stock.service.IStockService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

//由business模块调用，所以也需要进行注册
@DubboService
@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    //当前order模块消费stock模块的减少库存的功能
    //stock模块减少库存的方法已经注册到nacos中了，所以order模块可以利用Dubbo调用
    //要调用就必须添加@DubboReference注解，才能获得业务逻辑层实现类对象
    @DubboReference
    private IStockService stockService;
    //order也需要调用cart模块的删除购物车商品的功能
    @DubboReference
    private ICartService cartService;
    @Override
    public void orderAdd(OrderAddDTO orderAddDTO) {
        //1.减少库存--调用stock模块
        //stock模块中的功能需要的参数类型是StockReduceCountDTO类型
        StockReduceCountDTO stockReduceCountDTO = new StockReduceCountDTO();
        stockReduceCountDTO.setCommodityCode(orderAddDTO.getCommodityCode());
        stockReduceCountDTO.setReduceCount(orderAddDTO.getCount());
        stockService.reduceCommodityCount(stockReduceCountDTO);
        //2.删除购物车中选择的商品--调用cart模块
        cartService.deleteUserCart(orderAddDTO.getUserId(),orderAddDTO.getCommodityCode());
        //3.新增订单
        OrderTbl order = new OrderTbl();
        BeanUtils.copyProperties(orderAddDTO,order);
        //执行新增
        orderMapper.insertOrder(order);
        log.info("新增的订单信息为：{}",order);
    }

    //分页查询
    //pageNum是页码,pageSize是每页条数
    @Override
    public JsonPage<OrderTbl> getAllOrdersByPage(Integer pageNum, Integer pageSize){
        //使用PageHelper实现分页查询，需要设置分页条件
        PageHelper.startPage(pageNum,pageSize);
        //运行查询语句的时候，会自动在末尾追加limit关键字，条件也不需要人为计算
        List<OrderTbl> allOrders = orderMapper.findAllOrders();
        //上面的只是分页数据，如果想要分页信息，需要使用PageHelper提供的PageInto
        return JsonPage.restPage(new PageInfo<>(allOrders));
    }
}
